package com.lagou.handler;

import com.lagou.ServerBoot;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.springframework.stereotype.Component;
import org.springframework.util.backoff.ExponentialBackOff;

import java.io.InputStream;
import java.util.Properties;

/**
 * 服务注册 将服务端ip和端口注册到zk
 */
@Component
public class ZkServerHandler {

    public void registerToZk(int port) throws Exception {

        InputStream inputStream = ServerBoot.class.getClassLoader().getResourceAsStream("application.properties");
        Properties properties = new Properties();
        properties.load(inputStream);
        String zkServerUrl = properties.getProperty("zk.zkServerUrl");
        String rootPath = properties.getProperty("zk.zkRootPath");
        System.out.println("服务url："+zkServerUrl);
        System.out.println("节点根路径："+rootPath);

        String serverData = "localhost:" + port;

        System.out.println("注册到zk服务器的端口是="+port);
        //使用curator客户端连接zk客户端会话
        RetryPolicy retryPolicy =new ExponentialBackoffRetry(1000,3);

        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString(zkServerUrl)
                .sessionTimeoutMs(50000)
                .connectionTimeoutMs(30000)
                .retryPolicy(retryPolicy)
                .build();
        client.start();

        //在zk服务器创建rpc-provider
        //String rootPath="/rpc";

        //1,判断节点是否存在
        Stat stat = client.checkExists().forPath(rootPath);
        if(stat==null){
            client.create().creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT).forPath(rootPath);
            System.out.println("注册服务器根节点到zk服务器上了，节点路径为"+rootPath);
        }

        //节点存在，创建临时节点
        client.create().creatingParentsIfNeeded()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(rootPath+"/provider",serverData.getBytes());
        System.out.println("注册临时顺序节点到zk上，节点内容为 服务器:"+zkServerUrl+" 端口信息"+port);
    }
}
